package bot;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import fi.zem.aiarch.game.hierarchy.Board.Square;
import fi.zem.aiarch.game.hierarchy.Engine;
import fi.zem.aiarch.game.hierarchy.Move;
import fi.zem.aiarch.game.hierarchy.MoveType;
import fi.zem.aiarch.game.hierarchy.Piece;
import fi.zem.aiarch.game.hierarchy.Player;
import fi.zem.aiarch.game.hierarchy.Side;
import fi.zem.aiarch.game.hierarchy.Situation;

public class FooBarBot implements Player {
	private Side side;

	@Override
	public Move move(Situation situation, int timeLeft) {
		List<Move> moves = situation.legal(this.side);
		int value = Integer.MIN_VALUE;
		Move bestMove = null;
		for(Move move : moves){
			int tmp = alphabeta(situation.copyApply(move), 5, Integer.MIN_VALUE, Integer.MAX_VALUE, nextSide(side));
			if(value < tmp){
				value = tmp;
				bestMove = move;
			}
		}
		return bestMove;
	}

	private int calculateTypeScore(Move move) {
		switch (move.getType()) {
		case DESTROY:
			return 1000 * move.getTarget().getValue();
		case ATTACK:
			return 100 * move.getTarget().getValue();
		case MOVE:
			return 10;
		default:
			return 1;
		}
	}

	private int countScore(Situation situation) {
		Iterable<Square> piecesRed = situation.getBoard().pieces(Side.RED);
		Iterable<Square> piecesBlue = situation.getBoard().pieces(Side.BLUE);
		int redScore = 0;
		for (Square square : piecesRed) {
			redScore += square.getPiece().getValue();
		}
		int blueScore = 0;
		for (Square square : piecesBlue) {
			blueScore += square.getPiece().getValue();
		}

		if (side == Side.RED) {
			return redScore - blueScore;
		} else {
			return blueScore - redScore;
		}
	}

	public int alphabeta(Situation situation, int depth, int a, int b, Side side) {
		if (depth == 0 || situation.isFinished()) {
			return getSituationValue(situation);
		}
		if (this.side == side) {
			List<Move> moves = situation.legal(side);
			for (Move move : moves) {
				a = Math.max(
						a,
						alphabeta(situation.copyApply(move), depth - 1, a, b,
								nextSide(side)));
				if (b <= a)
					break;
			}
			return a;
		} else {
			List<Move> moves = situation.legal(side);
			for (Move move : moves) {
				b = Math.min(
						b,
						alphabeta(situation.copyApply(move), depth - 1, a, b,
								nextSide(side)));
				if (b <= a)
					break;
			}
			return b;
		}
	}

	private Side nextSide(Side side) {
		return side == Side.BLUE ? Side.RED : Side.BLUE;
	}

	private int getSituationValue(Situation situation) {
		// TODO Auto-generated method stub
		return -1;
	}

	@Override
	public void start(Engine engine, Side side) {
		this.side = side;
	}

}
